package eclMain;
import java.util.ArrayList;

/**This class is a doubly-linked list of buckets that each hold 1 second worth of recorded chat lines.
 * Buckets are added to the front, and removed from the back, every second.*/
//TODO: make sure that this actually removes duplicates that appear from multiple clients
//XXX: USE SETS!!!!!
public class BucketList {
	private int sizeLimit = 0;
	private ArrayList<ArrayList<ChatLine>> buckets = null;
	
	public BucketList(int cycleCount) {
		this.sizeLimit = cycleCount;
		this.buckets = new ArrayList<ArrayList<ChatLine>>(this.sizeLimit); //this is horribly inefficient....but at least I can debug it easily 
	}
	
	private void addBucket(ArrayList<ChatLine> lines) {
		this.buckets.add(0, lines);
	}
	
	private void removeLastBucket() {
		this.buckets.remove(this.buckets.size()-1);
	}
	
	private void cycleBuckets(ArrayList<ChatLine> lines) {
		addBucket(lines);
		removeLastBucket();
	}
	
	/**Removes duplicates from within the given list of chatLines, as well as removing duplicates from newLines that exist within previous cycles (default 5 seconds).
	 * Every time that this method is called, a bucket is added to the front of the list with the values of 'newLines', and one removed from the end.*/
	public ArrayList<ChatLine> removeDuplicates(ArrayList<ChatLine> newLines) {
		if (newLines == null || newLines.size() == 0) cycleBuckets(null);
		
		//remove any lines that appear more than once in newLines; ignore listener because I don't care who it comes from; ignore timestamp because it's all in the same bucket.
		ArrayList<ChatLine> temp = new ArrayList<ChatLine>();
		for (ChatLine line : newLines) {
			boolean found = false;
			for (ChatLine cl : temp) {
				if (cl.getOwner().equals(line.getOwner()) && cl.getText().equals(line.getText())) {
					found = true;
					break;
				}
				
			}
			if (!found) temp.add(line);
		}
		newLines = temp;
		
		for (ArrayList<ChatLine> bucket : this.buckets) {
			newLines = filterLines(newLines, bucket);
		}
		
		//cycle buckets
		cycleBuckets(newLines);
		return newLines;
	}
	
	/**Given a list of 'newLines', and a list to 'filterAgainst', this method will remove all lines from newLines that also exist in filterAgainst.
	 * This method does not account for the timestamp on chatLines from either ArrayList, or for the listener.*/
	private ArrayList<ChatLine> filterLines (ArrayList<ChatLine> newLines, ArrayList<ChatLine> filterAgainst) {
		ArrayList<ChatLine> returnLines = new ArrayList<ChatLine>();
		returnLines.addAll(newLines);
		
		for (ChatLine line : newLines) {
			for (ChatLine filterLine : filterAgainst) {
				if (filterLine.getChannel().getChannelID().equals(line.getChannel().getChannelID())) { //if channelIDs are the same
					if (filterLine.getOwner().equals(line.getOwner()) && filterLine.getText().equals(line.getText())) { //if the owners are the same as well as the text
						returnLines.remove(line); //don't add
					}
				}
			}
		}
		return returnLines;
	}
}
